package com.diandian.backend.file.service;

import com.diandian.backend.file.constants.FileConstant;
import com.diandian.backend.file.resp.FileInfoRespFile;
import com.diandian.base.boot.starter.exception.DefaultException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class FileRouterService {

    private static final Logger logger = LoggerFactory.getLogger(FileRouterService.class);

    @Autowired
    private LocalFileService localFileService;

    @Autowired
    private MinIOFileService minIOFileService;

    @Value("${oss.type}")
    private String ossType;

    /**
     * 上传到本地
     * 注意：一个MultipartFile对象不能在一个方法里多次使用
     */
    public FileInfoRespFile uploadToLocal(MultipartFile file) {

        // 校验文件本身格式是否与后缀一致
//        if(!FileUtil.fileExtensionCheck(file)){
//            throw new DefaultException(1, "文件不合法");
//        }
        return localFileService.saveFile(file);
    }

    /**
     * 上传到OSS服务路由
     * @param file
     * @return
     */
    public FileInfoRespFile uploadToOSS(MultipartFile file) {

        // 1. 校验文件本身格式是否与后缀一致
//        if(!FileUtil.fileExtensionCheck(file)){
//            throw new DefaultException(1, "文件不合法");
//        }

        if(FileConstant.OSS_TYPE_MINIO.equals(ossType)){
            return minIOFileService.saveFile(file);
        }

        throw new DefaultException("暂不支持OSS渠道：" + ossType);
    }

    /**
     * 从文件url存储到本地
     */
    public FileInfoRespFile urlToLocal(String fileName, String url) {
        return localFileService.saveFileFromUrl(fileName, url);
    }

}
